package org.cagiobox.contactfinder;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.NamedNodeMap;

public class InputSequencer {

	static Logger log = Logger.getLogger(InputSequencer.class.getName());

	public List<String> getURLList(String filePath) {

		List<String> URLList = new ArrayList<String>();

		try {

			File file = new File(filePath);

			DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();

			Document doc = dBuilder.parse(file);

			log.info("Root element:" + doc.getDocumentElement().getNodeName());

			Element root = doc.getDocumentElement();

			NodeList nodeList = root.getChildNodes();
			for (int count = 0; count < nodeList.getLength(); count++) {

				Node tempNode = nodeList.item(count);

				// make sure it's element node.
				if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

					// get node name and value
					log.info("Node Name:" + tempNode.getNodeName());
					log.debug("Node Value:" + tempNode.getTextContent());

					if (tempNode.hasAttributes()) {

						// get attributes names and values
						NamedNodeMap nodeMap = tempNode.getAttributes();

						for (int i = 0; i < nodeMap.getLength(); i++) {

							Node node = nodeMap.item(i);
							log.debug("attr name:" + node.getNodeName());

							if ("href".equalsIgnoreCase(node.getNodeName())) {

								URLList.add(node.getNodeValue());

							}

						}

						if (tempNode.hasChildNodes()) {

							// loop again if has child nodes

						}

					}

				}

			}
		} catch (Exception e) {
			log.error("Errore caricamento/parsing xml",e);
		}

		return URLList;
	}

}
